#!coding=utf-8

import socket
import os
import sys
import struct
import sys, getopt

#python testSendFile.py -d api -f modules/ShuaBao.Backend/resources/views/advert_source/include/advert_setting.blade.php
#修改项目路径
path_main = "D:/phpstudy_pro/WWW/tuiguang-sys-admin/"
def socket_client(deployment, file_list):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(('192.168.110.119', 9001))
    except socket.error as msg:
        print(msg)
        sys.exit(1)
    print(s.recv(1024))

    # 需要传输的文件路径
    # filepath = '/root/test.txt'
    for fileP in file_list:
        # 判断是否为文件
        filepath = path_main + fileP
        if os.path.isfile(filepath):
            # 定义定义文件信息。128s表示文件名为128bytes长，l表示一个int或log文件类型，在此为文件大小
            # fileinfo_size = struct.calcsize('128sl')
            # 定义文件头信息，包含文件名和文件大小
            fhead = struct.pack('128sl128s', fileP.encode('utf-8'), os.stat(filepath).st_size,
                                str(deployment).encode('utf-8'))
            # 发送文件名称与文件大小
            s.send(fhead)
            # 将传输文件以二进制的形式分多次上传至服务器
            fp = open(filepath, 'rb')
            while 1:
                data = fp.read(1024)
                if not data:
                    print('{0} file send over...'.format(os.path.basename(filepath)))
                    break
                s.send(data)
            # 关闭当期的套接字对象
    s.close()


if __name__ == '__main__':
    argv = sys.argv[1:]
    deployment = ''
    outputfile = ''
    try:
        opts, args = getopt.getopt(argv, "hd:f:", ["deployment=", "ifile="])
    except getopt.GetoptError:
        print('test.py -d <deployment> -f <inputfile>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('test.py -d <deployment> -f <inputfile>')
            sys.exit()
        elif opt in ("-d", "--deployment"):
            deployment = arg
        elif opt in ("-f", "--ifile"):
            outputfile = arg
    print('deployment：', deployment)
    file_list = outputfile.split(',')
    print('文件为：', file_list)
    if (len(file_list) <= 0):
        exit('没有上传的文件')
    socket_client(deployment, file_list)
